package com.onpositive.mediawiki.dataprocessors;

import java.util.HashMap;

import com.onpositive.mediawiki.propertyparser.PropertyCharacteristic;
import com.onpositive.units.ParsedProperty;
import com.onpositive.units.ParsedValue;

public class UniqueValuesCounter extends AbstractDataProcessor {
	
	private HashMap<Object,Integer> totalMap ; 
	private HashMap<String,HashMap<Object,Integer>> propertyMap ;


	public UniqueValuesCounter() {
		super();
	}
	
	@Override
	protected void readFlags(int flags) {}
		
	@Override
	protected boolean checkApplicability(PropertyCharacteristic pc) {
		return true;
	}

	@Override
	protected void doGatherPropertyStats(ParsedProperty prop) {
		
		if( propertyMap == null )
			propertyMap = new HashMap<String, HashMap<Object,Integer>>() ;
		
		String propertyName = prop.getName();
		HashMap<Object, Integer> pMap = propertyMap.get( propertyName ) ;
		if( pMap == null )
		{
			pMap = new HashMap<Object, Integer>() ;
			propertyMap.put( propertyName, pMap ) ;
		}
		
		for( ParsedValue pVal : prop.getValues() )
		{
			Object val = pVal.value() ;
			if( val != null )
			{
				Integer count = pMap.get(val) ;
				count = count != null ? count + 1 : 1 ;
				pMap.put( val, count ) ;
			}
		}
		
	}

	@Override
	protected void doGatherTotalStats(ParsedProperty prop) {
		
		if( totalMap == null )
			totalMap = new HashMap<Object, Integer>() ;
		
		for( ParsedValue pVal : prop.getValues() )
		{
			Object val = pVal.value() ;
			if( val != null )
			{
				Integer count = totalMap.get(val) ;
				count = count != null ? count + 1 : 1 ;
				totalMap.put( val, count ) ;
			}
		}
	}

	@Override
	protected void doApplyChanges(PropertyCharacteristic pc) {
		
		String propertyName = pc.getName() ;
		HashMap<Object,Integer> pMap = propertyMap.get( propertyName ) ;
		if( pMap != null ){
			int uniqueValuesCount = pMap.size() ;
			pc.setUniqueValuesCount( uniqueValuesCount ) ;
		}
		else{
			pc.setUniqueValuesCount( 0 ) ;
		}
	}

	@Override
	protected void doApplyPropertyChange(ParsedProperty prop) {}

	@Override
	protected void doApplayTotalChange(ParsedProperty prop) {}

}
